package com.zyzd.baseprojectofvolly.chat.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.media.ThumbnailUtils;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.hyphenate.chat.EMChatManager;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.ui.EaseChatFragment;
import com.hyphenate.easeui.ui.EaseChatFragment.EaseChatFragmentHelper;
import com.hyphenate.easeui.utils.EaseUserUtils;
import com.hyphenate.easeui.widget.chatrow.EaseChatRow;
import com.hyphenate.easeui.widget.chatrow.EaseCustomChatRowProvider;
import com.hyphenate.easeui.widget.emojicon.EaseEmojiconMenu;
import com.hyphenate.exceptions.HyphenateException;
import com.hyphenate.util.EasyUtils;
import com.hyphenate.util.PathUtil;
import com.zyzd.baseprojectofvolly.MainActivity;
import com.zyzd.baseprojectofvolly.R;
import com.zyzd.baseprojectofvolly.bean.local.RobotUser;
import com.zyzd.baseprojectofvolly.bean.remote.ApiResultBean;
import com.zyzd.baseprojectofvolly.chat.Constant;
import com.zyzd.baseprojectofvolly.chat.DemoHelper;
import com.zyzd.baseprojectofvolly.chat.activity.PickAtUserActivity;
import com.zyzd.baseprojectofvolly.chat.activity.VideoCallActivity;
import com.zyzd.baseprojectofvolly.chat.activity.VoiceCallActivity;
import com.zyzd.baseprojectofvolly.chat.bean.EmojiconExampleGroupData;
import com.zyzd.commontools.log.TLog;

import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;



public class ChatFragment extends EaseChatFragment implements EaseChatFragmentHelper {


    public static final int REQUEST_CODE_ADD_ORDER = 216;
    public static final int REQUEST_CODE_DOCTOR_LIST = 217;
    private static final int ITEM_IMAGE = 11;//选择照片
    private static final int ITEM_VIDEO = 12;//选择视频
    private static final int ITEM_INTRODUCTION = 13;//医疗机构：机构介绍
    private static final int ITEM_BUSINESS_CARD = 14;//个人名片
    private static final int ITEM_PHYSICIAN_INTRODUCTION = 15;//医师介绍
    private static final int ITEM_EXCLUSIVE_APPLICATION = 16;//申请专属
    private static final int ITEM_PROJECT_INTRODUCTION = 17;//项目介绍
    private static final int ITEM_ORDER = 18;//创建订单

    private static final int REQUEST_CODE_SELECT_AT_USER = 15;
    private static final int REQUEST_CODE_SELECT_IMAGE = 111;//选择照片

    private static final int REQUEST_CODE_INTRODUCTION = 113;//医疗机构：机构介绍
    private static final int REQUEST_CODE_BUSINESS_CARD = 114;//个人名片
    private static final int REQUEST_CODE_PHYSICIAN_INTRODUCTION = 115;//医师介绍
    private static final int REQUEST_CODE_EXCLUSIVE_APPLICATION = 116;//申请专属
    private static final int REQUEST_CODE_PROJECT_INTRODUCE = 117;//医师团队
    private static final int REQUEST_CODE_ORDER = 118;//项目介绍

    private static final int MESSAGE_TYPE_SENT_INSTITUTIONS_INTRODUCTION = 5;
    private static final int MESSAGE_TYPE_RECV_INSTITUTIONS_INTRODUCTION = 6;

    private static final int MESSAGE_TYPE_SENT_USINESS_CARD = 7;
    private static final int MESSAGE_TYPE_RECV_USINESS_CARD = 8;

    private static final int MESSAGE_TYPE_SENT_PHYSICIAN_INTRODUCTION = 9;
    private static final int MESSAGE_TYPE_RECV_PHYSICIAN_INTRODUCTION = 10;

    private static final int MESSAGE_TYPE_SENT_EXCLUSIVE_APPLICATION = 11;
    private static final int MESSAGE_TYPE_RECV_EXCLUSIVE_APPLICATION = 12;

    private static final int MESSAGE_TYPE_SENT_PROJECT_INTRODUCTION = 13;
    private static final int MESSAGE_TYPE_RECV_PROJECT_INTRODUCTION = 14;

    private static final int MESSAGE_TYPE_SENT_ORDER = 15;
    private static final int MESSAGE_TYPE_RECV_ORDER = 16;

    private static final int MESSAGE_TYPE_SENT_TEST = 17;
    private static final int MESSAGE_TYPE_RECV_TEST = 18;


//    public HospitalBean mHospitalBean;
//    public boolean isExclusive;
//    public ArrayList<UserBean> exclusiveList;
    public List<String> blackListFromServer;
    public boolean isInBlackList;
//    public ReminderDialog mDialog;
    protected int[] customItemStrings = {R.string.photo, R.string.video, R.string.medical_institution, R.string.delivery_info,
            R.string.physician_introduction, R.string.exclusive_application, R.string.project_introduction, R.string.create_order};
    protected int[] customItemdrawables = {R.drawable.ease_photo_selector, R.drawable.ease_video_selector,
            R.drawable.ease_medical_institution_selector, R.drawable.ease_delivery_info_normal,
            R.drawable.ease_physician_introduction_normal, R.drawable.ease_exclusive_application_normal,
            R.drawable.ease_project_introduction_normal, R.drawable.ease_create_order_normal};
    //end of red packet code
    protected int[] customItemIds = {ITEM_IMAGE, ITEM_VIDEO, ITEM_INTRODUCTION, ITEM_BUSINESS_CARD,
            ITEM_PHYSICIAN_INTRODUCTION, ITEM_EXCLUSIVE_APPLICATION, ITEM_PROJECT_INTRODUCTION, ITEM_ORDER};
    /**
     * if it is chatBot
     */
    private boolean isRobot;
    private String nickName;
//    private ExclusivesObserver.Subscribe subscribe = new ExclusivesObserver.Subscribe() {
//        @Override
//        public void onExclusivesChange(ArrayList<UserBean> exclusives) {
//            exclusiveList = exclusives;
//        }
//    };

    @Override
    protected int getLayoutId() {
        return R.layout.layout_fragment_chat;
    }

    @Override
    protected void setUpView() {
        setChatFragmentListener(this);
        if (chatType == Constant.CHATTYPE_SINGLE) {
            Map<String, RobotUser> robotMap = DemoHelper.getInstance().getRobotList();
            if (robotMap != null && robotMap.containsKey(toChatUsername)) {
                isRobot = true;
            }
        }
        super.setUpView();
        // set click listener
        titleBar.setLeftLayoutClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (EasyUtils.isSingleActivity(getActivity())) {
                    Intent intent = new Intent(getActivity(), MainActivity.class);
                    startActivity(intent);
                }
                onBackPressed();
            }
        });

        if (EaseUserUtils.getUserInfo(toChatUsername) != null) {
            EaseUser user = EaseUserUtils.getUserInfo(toChatUsername);
            if (user != null) {
                nickName = user.getNickname();
            }
        }

        ((EaseEmojiconMenu) inputMenu.getEmojiconMenu()).addEmojiconGroup(EmojiconExampleGroupData.getData());
        if (chatType == EaseConstant.CHATTYPE_GROUP) {
            inputMenu.getPrimaryMenu().getEditText().addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    if (count == 1 && "@".equals(String.valueOf(s.charAt(start)))) {
                        startActivityForResult(new Intent(getActivity(), PickAtUserActivity.class).
                                putExtra("groupId", toChatUsername), REQUEST_CODE_SELECT_AT_USER);
                    }
                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });
        }

        //修改右上方按钮显示
        updateRightLayout();
        //设置是否可以发送消息
        if (openFrom != 1 && isInBlackList) {
            changeToUnChatState();
        }
    }

    /**
     * 更新右上方按钮状态
     */
    private void updateRightLayout() {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                updateRightLayoutTask();
            }
        });

    }

    /**
     * 更新右上方按钮状态任务
     */
    private void updateRightLayoutTask() {
        //存在空指针的可能性，异步更新造成的
        if (titleBar == null) {
            return;
        }
//        titleBar.setRightText(isExclusive ? "取消专属" : "结束咨询");
//        titleBar.setRightTextVisiable(View.VISIBLE);
//        titleBar.setRightLayoutVisibility(isExclusive || openFrom == 1 ? View.VISIBLE : isInBlackList ? View.GONE : View.VISIBLE);

//        titleBar.setRightLayoutClickListener(new OnClickListener() {
//
//
//            @Override
//            public void onClick(View v) {
//
//                if (isExclusive) {
//                    //取消专属
//                    mDialog = DialogHelper.openReminderCloseDialog(getActivity(), "取消专属", "是否取消与" + nickName + "的专属关系", new ReminderDialog.OnPositiveListener() {
//                        @Override
//                        public void onPositive() {
//                            cancelExclusive();
//                        }
//                    });
//                } else {
//                    mDialog = DialogHelper.openReminderCloseDialog(getActivity(), "结束咨询", "结束咨询后，将无法给对方发送消息，确认结束本次咨询吗？", new ReminderDialog.OnPositiveListener() {
//                        @Override
//                        public void onPositive() {
//                            endConsultation();
//                        }
//                    });
//                }
//            }
//        });
    }

    /**
     * 结束咨询
     */
//    private void endConsultation() {
//        //发送透传消息，通知对方结束盖该次的咨询，将禁用聊天
//        EMMessage cmdMsg = EMMessage.createSendMessage(EMMessage.Type.CMD);
////                //支持单聊和群聊，默认单聊，如果是群聊添加下面这行
//        cmdMsg.setChatType(EMMessage.ChatType.Chat);
//        String action = "intercept";//action可以自定义
//        EMCmdMessageBody cmdBody = new EMCmdMessageBody(action);
//        cmdMsg.setTo(toChatUsername);
//        cmdMsg.addBody(cmdBody);
//        EMClient.getInstance().chatManager().sendMessage(cmdMsg);
//
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    EMClient.getInstance().contactManager().addUserToBlackList(toChatUsername, false);
//                    isInBlackList = true;
//                    updateRightLayout();
//                    changeToUnChatState();
//                } catch (HyphenateException e) {
//                    e.printStackTrace();
//                }
//            }
//        }).start();
//    }

    /**
     * 取消专属
     */
//    private void cancelExclusive() {
//        String apiFriendDelete = UrlUtil.API_FRIEND_DELETE;
//        Map<String, String> params = UrlUtil.getBaseRequestMap(apiFriendDelete);
//        params.put("object_id", toChatUsername);
//        VolleyHelper.stringRequest(UrlUtil.getRequestUrl(apiFriendDelete), getClass().getSimpleName(), params, new Response.Listener<String>() {
//            @Override
//            public void onResponse(String response) {
//                if (TextUtils.isEmpty(response)) {
//                    showToast("请求取消专属失败！");
//                    return;
//                }
//
//                try {
//                    ApiResultBean resultBean = new Gson().fromJson(response, ApiResultBean.class);
//                    if (resultBean == null || resultBean.getError_no() != ErrorCodeUtil.ERROR_000001) {
//                        showToast("请求取消专属失败！");
//                        return;
//                    }
//
//                    //移除专属成功,更新专属列表
//                    ArrayList<UserBean> exclusiveList = UserHelper.getExclusiveList();
//                    for (UserBean userBean : exclusiveList) {
//                        if (userBean.getUser_id().equals(toChatUsername)) {
//                            exclusiveList.remove(userBean);
//                            break;
//                        }
//                    }
//                    UserHelper.updateExclusiveList(exclusiveList);
//                    //重新加载底部菜单栏，检查是否显示结束咨询
//                    isExclusive = false;
//                    updateRightLayout();
//
//                    //发送透传消息，通知对方取消专属
//                    EMMessage cmdMsg = EMMessage.createSendMessage(EMMessage.Type.CMD);
//
//                    cmdMsg.setChatType(EMMessage.ChatType.Chat);
//                    String action = "removeExclusive";//action可以自定义
//                    EMCmdMessageBody cmdBody = new EMCmdMessageBody(action);
//                    cmdMsg.setTo(toChatUsername);
//                    cmdMsg.addBody(cmdBody);
//                    EMClient.getInstance().chatManager().sendMessage(cmdMsg);
//
//                } catch (JsonSyntaxException e) {
//                    e.printStackTrace();
//                }
//
//
//            }
//        }, new Response.ErrorListener() {
//            @Override
//            public void onErrorResponse(VolleyError error) {
//                showToast("网络访问失败！");
//            }
//        });
//    }

    @Override
    protected void initView() {
        //该列表数据在此获取的时机较好
        getExclusiveAndBlackList();
        super.initView();
    }

    /**
     * 获取专属列表和黑名单，并判断是否在对方在两列表的状态
     */
    private void getExclusiveAndBlackList() {
        //是否在专属列表
//        exclusiveList = UserHelper.getExclusiveList();
//        ExclusivesObserver.register(subscribe);
//        if (exclusiveList == null) exclusiveList = new ArrayList<>();
//        for (UserBean userBean : exclusiveList) {
//            if (userBean.getUser_id().equals(toChatUsername)) {
//                isExclusive = true;
//                break;
//            }
//        }
        //判断是否在黑名单中
        blackListFromServer = EMClient.getInstance().contactManager().getBlackListUsernames();
        if (blackListFromServer != null && blackListFromServer.contains(toChatUsername)) {
            isInBlackList = true;
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
//        if (openFrom == 1) {
//            new Handler().postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    if (UserHelper.getUserInfo() != null) {
//                        sendTextMessage("您好，我是咨询师" + UserHelper.getUserInfo().getNickname());
//                        openFrom = 0;
//                    }
//                }
//            }, 1500);//设置一定时间后发送是提高发送成功率，因为双方黑名单控制，需要一定的反馈时间
//        }
    }

    @Override
    protected void registerExtendMenuItem() {
        //use the menu in base class
//        super.registerExtendMenuItem();
        //extend menu items
        //TODO 注册软件盘item
        for (int i = 0; i < customItemdrawables.length; i++) {
            inputMenu.registerExtendMenuItem(customItemStrings[i], customItemdrawables[i], customItemIds[i], extendMenuItemClickListener);
        }

//        if (chatType == Constant.CHATTYPE_SINGLE) {
//            inputMenu.registerExtendMenuItem(R.string.attach_voice_call, R.drawable.em_chat_voice_call_selector, ITEM_VOICE_CALL, extendMenuItemClickListener);
//            inputMenu.registerExtendMenuItem(R.string.attach_video_call, R.drawable.em_chat_video_call_selector, ITEM_VIDEO_CALL, extendMenuItemClickListener);
//        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        TLog.d("zyzd", "ChatFragment>>onActivityResult--> " + requestCode);
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
//        switch (requestCode) {
//            case PickUtil.REQUEST_IMAGE://发送图片
//                ArrayList<String> images = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
//                images.get(0);
//                sendImageMessage(images.get(0));
//                break;
//            case PickUtil.REQUEST_STORAGE_READ_ACCESS_PERMISSION://请求权限成功后再次打开图片选择
//                PickUtil.pickImage(this, false);
//                break;
//            case PickUtil.REQUEST_STORAGE_READ_ACCESS_PERMISSION_VIDEO:
//                PickUtil.pickVideo(this);
//                break;
//            case PickUtil.REQUEST_CODE_SELECT_VIDEO: //发送视频
//                if (data != null) {
//                    int duration = data.getIntExtra("dur", 0);
//                    String videoPath = data.getStringExtra("path");
//                    File file = new File(PathUtil.getInstance().getImagePath(), "thvideo" + System.currentTimeMillis());
//                    try {
//                        FileOutputStream fos = new FileOutputStream(file);
//                        Bitmap ThumbBitmap = ThumbnailUtils.createVideoThumbnail(videoPath, 3);
//                        ThumbBitmap.compress(CompressFormat.JPEG, 100, fos);
//                        fos.close();
//                        sendVideoMessage(videoPath, file.getAbsolutePath(), duration);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                }
//                break;
//
//            case REQUEST_CODE_DOCTOR_LIST://医师列表
//                if (data != null) {
//                    DoctorBean doctorBean = (DoctorBean) data.getSerializableExtra(DoctorFragment.EXTRA_DOCTOR_INFO);
//                    sendDoctorIntroduction(doctorBean);
//                }
//                break;
//            case REQUEST_CODE_PROJECT_INTRODUCE://项目介绍
//                if (data != null) {
//                    ProjectBean projectBean = data.getParcelableExtra(AllProjectActivity.EXTRA_SELECTED_ROJECT);
//                    if (projectBean != null) {
//                        sendProjectIndroduction(projectBean);
//                    }
//
//                }
//                break;
//            case REQUEST_CODE_ADD_ORDER:
//                if (data != null) {
//                    String orderId = data.getStringExtra("orderId");
//                    String content = data.getStringExtra("content");
//                    String title = data.getStringExtra("title");
//                    String image = data.getStringExtra("image");
//                    sendOrder(orderId, content, title, image);
//                }
//                break;
//            case REQUEST_CODE_SELECT_AT_USER:
//                if (data != null) {
//                    String username = data.getStringExtra("username");
//                    inputAtUsername(username, false);
//                }
//                break;
//            default:
//                break;
//        }


    }

    @Override
    public void onSetMessageAttributes(EMMessage message) {
        if (isRobot) {
            //set message extension
            message.setAttribute("em_robot_message", isRobot);
        }

//        PersonInfoBean userInfo = UserHelper.getUserInfo();
//        if (userInfo != null) {
//            TLog.d("zyzd", "ChatFragment>>onSetMessageAttributes-nickname-> " + userInfo.getNickname());
//            TLog.d("zyzd", "ChatFragment>>onSetMessageAttributes-avater-> " + userInfo.getHead_img_url());
//            message.setAttribute(Constant.MESSAGE_ATTR_AVATER, userInfo.getHead_img_url());
//            message.setAttribute(Constant.MESSAGE_ATTR_NICKNAME, userInfo.getNickname());
//            message.setAttribute(Constant.MESSAGE_ATTR_TYPE, 1);
//        }

    }

    @Override
    public EaseCustomChatRowProvider onSetCustomChatRowProvider() {
        return new CustomChatRowProvider();
    }


    @Override
    public void onEnterToChatDetails() {
//        if (chatType == Constant.CHATTYPE_GROUP) {
//            EMGroup group = EMClient.getInstance().groupManager().getGroup(mToChatUsername);
//            if (group == null) {
//                Toast.makeText(getActivity(), R.string.gorup_not_found, Toast.LENGTH_SHORT).show();
//                return;
//            }
//            startActivityForResult(
//                    (new Intent(getActivity(), GroupDetailsActivity.class).putExtra("groupId", mToChatUsername)),
//                    REQUEST_CODE_GROUP_DETAIL);
//        }else if(chatType == Constant.CHATTYPE_CHATROOM){
//        	startActivityForResult(new Intent(getActivity(), ChatRoomDetailsActivity.class).putExtra("roomId", mToChatUsername), REQUEST_CODE_GROUP_DETAIL);
//        }
    }

    @Override
    public void onAvatarClick(String username) {
        //handling when user click avatar
        //TODO 点击头像
//        Intent intent = new Intent(getActivity(), UserProfileActivity.class);
//        intent.putExtra("username", username);
//        startActivity(intent);
    }

    @Override
    public void onAvatarLongClick(String username) {
        inputAtUsername(username);
    }


    @Override
    public boolean onMessageBubbleClick(EMMessage message) {
        //消息框点击事件，demo这里不做覆盖，如需覆盖，return true
        //red packet code : 拆红包页面
//        if (message.getBooleanAttribute(RPConstant.MESSAGE_ATTR_IS_RED_PACKET_MESSAGE, false)){
//            if (RedPacketUtil.isRandomRedPacket(message)){
//                RedPacketUtil.openRandomPacket(getActivity(),message);
//            } else {
//                RedPacketUtil.openRedPacket(getActivity(), chatType, message, mToChatUsername, messageList);
//            }
//            return true;
//        } else if (message.getBooleanAttribute(RPConstant.MESSAGE_ATTR_IS_TRANSFER_PACKET_MESSAGE, false)) {
//            RedPacketUtil.openTransferPacket(getActivity(), message);
//            return true;
//        }
//        //end of red packet code
        return false;
    }

    @Override
    public void onCmdMessageReceived(List<EMMessage> messages) {
        //对方结束咨询，将其加入黑名单进行控制，修改聊天状态为不可聊
        for (EMMessage message : messages) {
            TLog.d("zyzd", "ChatFragment>>onCmdMessageReceived--> ");
            EMCmdMessageBody cmdMsgBody = (EMCmdMessageBody) message.getBody();
            final String action = cmdMsgBody.action();//获取自定义action
//            if ("intercept".equals(action)) {
//                onReceivedIntercept();
//            } else if ("agreeAddExclusive".equals(action)) {
//                onReceivedAgreeAddExclusive(message);
//            } else if ("removeExclusive".equals(action)) {
//                onReceivedRemoveExclusive();
//            }
        }
        //end of red packet code
        super.onCmdMessageReceived(messages);
    }

    /**
     * 接收到移除专属的透传消息
     */
    private void onReceivedRemoveExclusive() {
//        isExclusive = false;
//        updateRightLayout();
//        for (UserBean userBean : exclusiveList) {
//            if (userBean.getUser_id().equals(toChatUsername)) {
//                exclusiveList.remove(userBean);
//                UserHelper.updateExclusiveList(exclusiveList);
//                break;
//            }
//        }
    }

    /**
     * 接收到同意添加专属的透传消息
     */
//    private void onReceivedAgreeAddExclusive(EMMessage message) {
//        TLog.d("zyzd", "ChatFragment>>onCmdMessageReceived--> agreeAddExclusive");
//        //同意了添加专属就显示右上角的取消专属
////        isExclusive = true;
//        updateRightLayout();
//        //重新请求好友列表
//        LocalBroadcastManager.getInstance(getContext().getApplicationContext()).sendBroadcast(new Intent(Constant.ACTION_RE_REQUEST_EXCLUSIVE));
//        try {
//            String msgId = message.getStringAttribute("msgId");
//
//            if (!TextUtils.isEmpty(msgId)) {
//                EMChatManager emChatManager = EMClient.getInstance().chatManager();
//                EMMessage message1 = emChatManager.getMessage(msgId);
//                message1.setAttribute("isAgreenExclusive", true);
//                final String nickname = message1.getStringAttribute(Constant.MESSAGE_ATTR_NICKNAME);
//
//                emChatManager.updateMessage(message1);
//                getActivity().runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        messageList.refresh();
//                        showToast(nickname + "已同意您的专属添加申请，可以前往我的专属查看");
//                    }
//                });
//            }
//
//        } catch (HyphenateException e) {
//            e.printStackTrace();
//        }
//    }

    /**
     * 接收到结束咨询的透传消息
     */
    private void onReceivedIntercept() {
        TLog.d("zyzd", "ChatFragment>>onCmdMessageReceived--> intercept");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    isInBlackList = true;
                    updateRightLayout();
                    changeToUnChatState();
                    EMClient.getInstance().contactManager().addUserToBlackList(toChatUsername, false);
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void changeToUnChatState() {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                inputMenu.getPrimaryMenu().unClick();
                inputMenu.getExtendMenu().setVisibility(View.GONE);
                inputMenu.getEmojiconMenu().setVisibility(View.GONE);
                inputMenu.hideKeyboard();
            }
        });
    }

    @Override
    public void onMessageBubbleLongClick(EMMessage message) {
//    	// no message forward when in chat room
//        startActivityForResult((new Intent(getActivity(), ContextMenuActivity.class)).putExtra("message",message)
//                .putExtra("ischatroom", chatType == EaseConstant.CHATTYPE_CHATROOM),
//                REQUEST_CODE_CONTEXT_MENU);
    }

    @Override
    public boolean onExtendMenuItemClick(int itemId, View view) {
        Bundle bundle = new Bundle();
        TLog.d("zyzd", "ChatFragment>>onExtendMenuItemClick--> " + itemId);
//        switch (itemId) {
//            case ITEM_IMAGE://选择照片
//                PickUtil.pickImage(this, false);
//                break;
//            case ITEM_VIDEO://选择视频
//                PickUtil.pickVideo(this);
////                Intent intent = new Intent(getActivity(), ImageGridActivity.class);
////                startActivityForResult(intent, PickUtil.REQUEST_CODE_SELECT_VIDEO);
//                break;
//            case ITEM_INTRODUCTION://医疗机构：机构介绍
//                if (mHospitalBean != null) {
//                    sendInstitutionsIntroduction(mHospitalBean);
//                } else {
//                    requestHospitalInfo();
//                }
//                break;
//            case ITEM_BUSINESS_CARD://个人名片
//                sendBusinessCard();
//                break;
//            case ITEM_PHYSICIAN_INTRODUCTION://医师介绍
//                //sendDoctorIntroduction();
//                PersonInfoBean userInfo = UserHelper.getUserInfo();
//                if (userInfo != null) {
//                    bundle.putString(DoctorFragment.EXTRA_HOSPITAL_ID, userInfo.getHospital_id());
//                    UIHelper.openDoctorsActiviry(this, bundle);
//                } else {
//                    showToast("用户信息已过期，请重新登录");
//                }
//                break;
//            case ITEM_EXCLUSIVE_APPLICATION://申请专属
//                if (isExclusive) {
//                    showToast(nickName + "已经是您的专属用户了！");
//                } else {
//                    sendApplyAddExclusive();
//                }
//                break;
//            case ITEM_PROJECT_INTRODUCTION://项目介绍
//                bundle.putInt(AllProjectActivity.EXTRA_MODE, AllProjectActivity.MODE_SINGLE);
//                UIHelper.openAllProjectActivity(this, bundle, REQUEST_CODE_PROJECT_INTRODUCE);
//                break;
//            case ITEM_ORDER: //创建订单
//                bundle.putString("toChatUsername", toChatUsername);
//                UIHelper.openCreateOrderActivity(this, bundle);
//                //sendOrder();
//                break;
//
//
//            //end of red packet code
//            default:
//                break;
//        }
        //keep exist extend menu
        return false;
    }

//    /**
//     * 项目介绍
//     */
//    private void sendProjectIndroduction(ProjectBean project) {
//        EMMessage message = EMMessage.createTxtSendMessage("[项目介绍]", toChatUsername);
//
//        ChatRowProjectBean projectBean = new ChatRowProjectBean();
//        projectBean.setProjectId(project.getProject_id());
//        projectBean.setProjectName(project.getProject_name());
//
//        String img = "";
//        for (ProjectBean.ImageBean imageBean : project.getImage()) {
//            if (!TextUtils.isEmpty(imageBean.getImage_url())) {
//                img = imageBean.getImage_url();
//                break;
//            }
//        }
//        projectBean.setImage(img);
//        projectBean.setIntroduce(project.getTreatment());
//        TLog.d("zyzd", "ChatFragment>>sendProjectIndroduction--> " + new Gson().toJson(projectBean));
//        // 增加自己特定的属性
//        message.setAttribute(Constant.MESSAGE_ATTR_IS_PROJECT_INTRODUCTION, true);
//        message.setAttribute("jsonData", new Gson().toJson(projectBean));
//        sendMessage(message);
//    }

//    /**
//     * 医师介绍
//     *
//     * @param doctorBean
//     */
//    private void sendDoctorIntroduction(DoctorBean doctorBean) {
//        EMMessage message = EMMessage.createTxtSendMessage("[医师介绍]", toChatUsername);
//
//        ChatRowPhysicianBean chatRowDoctorBean = new ChatRowPhysicianBean();
//        chatRowDoctorBean.setDoctorId(doctorBean.getDoctor_id());
//        chatRowDoctorBean.setNickname(doctorBean.getDoctor_name());
//        chatRowDoctorBean.setHeadImage(doctorBean.getHead_img_url());
//        chatRowDoctorBean.setProfessional(doctorBean.getProfessional());
//        TLog.d("zyzd", "ChatFragment>>sendDoctorIntroduction--> " + new Gson().toJson(chatRowDoctorBean));
//        // 增加自己特定的属性
//        message.setAttribute(Constant.MESSAGE_ATTR_IS_HYSICIAN_INTRODUCTION, true);
//        message.setAttribute("jsonData", new Gson().toJson(chatRowDoctorBean));
//        sendMessage(message);
//    }

    /**
     * 添加专属
     */
    private void sendApplyAddExclusive() {

        EMMessage message = EMMessage.createTxtSendMessage("[添加专属申请]", toChatUsername);

        message.setAttribute(Constant.MESSAGE_ATTR_IS_APPLY_ADD_EXCLUSIVE, true);
        message.setAttribute("jsonData", "1");
        sendMessage(message);
    }

    /**
     * 发送机构介绍
     */
//    private void sendInstitutionsIntroduction(HospitalBean hospitalBean) {
//
//        this.mHospitalBean = hospitalBean;
//        EMMessage message = EMMessage.createTxtSendMessage("[机构介绍]", toChatUsername);
//
//        ChatRowIntroductionBean chatRowIntroductionBean = new ChatRowIntroductionBean();
//
//        chatRowIntroductionBean.setHospitalId(hospitalBean.getHospital_id());
//        List<HospitalBean.ImageBean> images = hospitalBean.getImage();
//        String hospitalImage = "";
//        if (images != null && images.size() >= 2) {
//            hospitalImage = images.get(1).getImage_url();
//        }
//
//        chatRowIntroductionBean.setImage(hospitalImage);
//        chatRowIntroductionBean.setHospitalName(TextUtils.isEmpty(hospitalBean.getHospital_name()) ? "医院名称" : hospitalBean.getHospital_name());
//        chatRowIntroductionBean.setIntroduction(hospitalBean.getDescribe());
//
//        TLog.d("zyzd", "ChatFragment>>sendInstitutionsIntroduction--> " + new Gson().toJson(chatRowIntroductionBean));
//        // 增加自己特定的属性
//        message.setAttribute(Constant.MESSAGE_ATTR_IS_INTRODUCTION, true);
//        message.setAttribute("jsonData", new Gson().toJson(chatRowIntroductionBean));
//        sendMessage(message);
//        TLog.d("zyzd", "ChatFragment>>sendInstitutionsIntroduction--> " + message.toString());
//
//
//    }

    /**
     * post请求
     * <p>
     * 默认使用getClass().getSimpleName()作为tag
     */
//    protected void requestHospitalInfo() {
//
//
//        PersonInfoBean userInfo = UserHelper.getUserInfo();
//        if (userInfo == null) {
//            return;
//        }
//
//        String hospital_id = userInfo.getHospital_id();
//
//        if (TextUtils.isEmpty(hospital_id)) {
//            return;
//        }
//
//        Map<String, String> params = UrlUtil.getBaseRequestMap(UrlUtil.API_HOSPITAL_INFO);
//        params.put("hospital_id", hospital_id);
//
//        VolleyHelper.stringRequest(UrlUtil.getRequestUrl(UrlUtil.API_HOSPITAL_INFO), getClass().getSimpleName(), params, new Response.Listener<String>() {
//            @Override
//            public void onResponse(String response) {
//
//                if (StringUtils.isEmpty(response)) {
//                    TLog.d("zyzd", "ChatFragment>>onResponse--> " + getString(R.string.requestError_emptyData));
//                    return;
//                }
//
//                try {
//                    ApiResultBean<HospitalBean> resultBean = new Gson().fromJson(response, getType());
//
//                    if (resultBean == null) {
//                        TLog.d("zyzd", "ChatFragment>>onResponse--> resultBean is null");
//                        return;
//                    }
//
//                    if (resultBean.getError_no() != ErrorCodeUtil.ERROR_000001) {
//                        TLog.d("zyzd", "ChatFragment>>onResponse--> onRequestErrorNo--> errorNo:" + resultBean.getError_no() + "  message:" + resultBean.getMsg());
//                        return;
//                    }
//                    if (resultBean.getData() == null) {
//                        TLog.d("zyzd", "ChatFragment>>onResponse--> data is null");
//                    } else {
//                        sendInstitutionsIntroduction(resultBean.getData());
//                    }
//                } catch (JsonSyntaxException e) {
//                    e.printStackTrace();
//                    TLog.d("zyzd", getClass().getSimpleName() + ">>onSuccses--> " + getString(R.string.requestError_JsonSyntaxException));
//                } catch (Exception e) {
//                    TLog.d("zyzd", getClass().getSimpleName() + ">>onSuccess--> otherException：" + e.getMessage());
//                }
//            }
//        }, new Response.ErrorListener() {
//            @Override
//            public void onErrorResponse(VolleyError error) {
//                Toast.makeText(getContext(), "网络请求失败", Toast.LENGTH_SHORT).show();
//            }
//        });
//    }


//    protected Type getType() {
//        return new TypeToken<ApiResultBean<HospitalBean>>() {
//        }.getType();
//    }

    /**
     * 发送订单
     *
     * @param orderId
     * @param content
     * @param title
     * @param image
     */
//    private void sendOrder(String orderId, String content, String title, String image) {
//        EMMessage message = EMMessage.createTxtSendMessage("[订单]", toChatUsername);
//
//        ChatRowOrderBean chatRowOrderBean = new ChatRowOrderBean();
//        chatRowOrderBean.setImage(image);
//        chatRowOrderBean.setTitle(title);
//        chatRowOrderBean.setIntroduce(content);
//        chatRowOrderBean.setOrderId(orderId);
//
//        // 增加自己特定的属性
//        message.setAttribute(Constant.MESSAGE_ATTR_IS_ORDER, true);
//        TLog.d("zyzd", "ChatFragment>>sendOrder--> " + new Gson().toJson(chatRowOrderBean));
//        message.setAttribute("jsonData", new Gson().toJson(chatRowOrderBean));
//        sendMessage(message);
//    }

    /**
     * 发送名片
     */
//    private void sendBusinessCard() {
//
//        EMMessage message = EMMessage.createTxtSendMessage("[咨询师名片]", toChatUsername);
//
//        ChatRowCardBean chatRowCardBean = new ChatRowCardBean();
//        PersonInfoBean userInfo = UserHelper.getUserInfo();
//        chatRowCardBean.setHeadImage(userInfo.getHead_img_url());
//        chatRowCardBean.setCounselorId(userInfo.getCounselor_id());
//        chatRowCardBean.setNickname(userInfo.getNickname());
//        chatRowCardBean.setHospital(userInfo.getHospital_name());
//
//        // 增加自己特定的属性
//        message.setAttribute(Constant.MESSAGE_ATTR_IS_BUSINESS_CARD, true);
//        TLog.d("zyzd", "ChatFragment>>sendBusinessCard--> " + new Gson().toJson(chatRowCardBean));
//        message.setAttribute("jsonData", new Gson().toJson(chatRowCardBean));
//        sendMessage(message);
//    }

    /**
     * make a voice call
     */
    protected void startVoiceCall() {
        if (!EMClient.getInstance().isConnected()) {
            Toast.makeText(getActivity(), R.string.not_connect_to_server, Toast.LENGTH_SHORT).show();
        } else {
            startActivity(new Intent(getActivity(), VoiceCallActivity.class).putExtra("username", toChatUsername)
                    .putExtra("isComingCall", false));
            // voiceCallBtn.setEnabled(false);
            inputMenu.hideExtendMenuContainer();
        }
    }

    /**
     * make a video call
     */
    protected void startVideoCall() {
        if (!EMClient.getInstance().isConnected())
            Toast.makeText(getActivity(), R.string.not_connect_to_server, Toast.LENGTH_SHORT).show();
        else {
            startActivity(new Intent(getActivity(), VideoCallActivity.class).putExtra("username", toChatUsername)
                    .putExtra("isComingCall", false));
            // videoCallBtn.setEnabled(false);
            inputMenu.hideExtendMenuContainer();
        }
    }

    public void showToast(String msg) {
        if (TextUtils.isEmpty(msg))
            return;
        Toast.makeText(getContext().getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//        DialogHelper.closeDialog(mDialog);
//        ExclusivesObserver.unRegister(subscribe);
    }

    /**
     * chat row provider
     */
    private final class CustomChatRowProvider implements EaseCustomChatRowProvider {
        @Override
        public int getCustomChatRowTypeCount() {
            //here the number is the message type in EMMessage::Type
            //which is used to count the number of different chat row
            return 18;
        }

        @Override
        public int getCustomChatRowType(EMMessage message) {
            if (message.getType() == EMMessage.Type.TXT) {

                if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_INTRODUCTION, false)) {
                    //医疗机构
                    return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_INSTITUTIONS_INTRODUCTION : MESSAGE_TYPE_SENT_INSTITUTIONS_INTRODUCTION;

                } else if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_BUSINESS_CARD, false)) {
                    //名片
                    return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_USINESS_CARD : MESSAGE_TYPE_SENT_USINESS_CARD;

                } else if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_HYSICIAN_INTRODUCTION, false)) {
                    //医师介绍
                    return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_PHYSICIAN_INTRODUCTION : MESSAGE_TYPE_SENT_PHYSICIAN_INTRODUCTION;

                } else if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_APPLY_ADD_EXCLUSIVE, false)) {
                    //申请专属
                    return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_EXCLUSIVE_APPLICATION : MESSAGE_TYPE_SENT_EXCLUSIVE_APPLICATION;

                } else if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_PROJECT_INTRODUCTION, false)) {
                    //项目介绍
                    return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_PROJECT_INTRODUCTION : MESSAGE_TYPE_SENT_PROJECT_INTRODUCTION;

                } else if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_ORDER, false)) {
                    //订单
                    return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_ORDER : MESSAGE_TYPE_SENT_ORDER;
                } else if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_TEST, false)) {
                    //订单
                    return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_TEST : MESSAGE_TYPE_SENT_TEST;
                }

                //end of red packet code
            }
            return 0;
        }

        @Override
        public EaseChatRow getCustomChatRow(EMMessage message, int position, BaseAdapter adapter) {
            if (message.getType() == EMMessage.Type.TXT) {
                // voice call or video call
//                if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VOICE_CALL, false) ||
//                        message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VIDEO_CALL, false)) {
//                    return new ChatRowVoiceCall(getActivity(), message, position, adapter);
//                } else if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_INTRODUCTION, false)) {
//                    //机构介绍
//                    return new ChatRowIntroduction(getActivity(), message, position, adapter);
//                } else if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_HYSICIAN_INTRODUCTION, false)) {
//                    //医师介绍
//                    return new ChatRowPhysicianIntroduction(getActivity(), message, position, adapter);
//                } else if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_BUSINESS_CARD, false)) {
//                    //名片
//                    return new ChatRowBusinessCard(getActivity(), message, position, adapter);
//                } else if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_APPLY_ADD_EXCLUSIVE, false)) {
//                    //添加专属
//                    return new ChatRowAddExclusive(getActivity(), message, position, adapter);
//                } else if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_PROJECT_INTRODUCTION, false)) {
//                    //项目介绍
//                    return new ChatRowProjectIntroduction(getActivity(), message, position, adapter);
//                } else if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_ORDER, false)) {
//                    //订单
//                    return new ChatRowOrder(getActivity(), message, position, adapter);
//                } else if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_TEST, false)) {
//                    //提示条目
//                    return new HintRow(getActivity(), message, position, adapter);
//                }
                //end of red packet code
            }
            return null;
        }
    }
}
